package server;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Iterator;

import netPacks.message;

public class backupPinger extends Thread{
    backupServer serverToPing = null;
	public int pingCnt = 3;
	
	public backupPinger(backupServer b){
		this.serverToPing = b;
	}
    
    public synchronized void run(){
    	message ping = new message();
		ping.setAction("pingFR");
		try {
			ping.setUserId(InetAddress.getLocalHost());
		} 
		catch (UnknownHostException e2) {
			e2.printStackTrace();
		}
    	
		while(this.pingCnt>0){
    			System.out.println("Sending ping check...");
        		this.pingCnt = this.pingCnt - 1;
        		try {
    				this.serverToPing.oos.writeObject(ping);
    			} 
        		catch (IOException e) {
        	    			System.out.println("Cannot send ping to client.");
        	    }
        		try {
    				Thread.sleep(1000);
    			}
        		catch (InterruptedException e) {
    				e.printStackTrace();
    			}
    		}
        
    	try {
			InetAddress tempId = this.clientToPing.getClientId();
        	this.clientToPing = null;
        	System.out.println("Removed clienttoping from Pingy");
			boolean tempFlag = false;
        	for(Iterator<clientConnection> it=mainServer.getInstance().userQ.iterator(); it.hasNext(); ){
				clientConnection tmp = it.next();
				if(tmp.getClientId().equals(tempId)){
					it.remove();
					tempFlag = true;
					break;
				}
			}
        	System.out.println("removed client from userQ");
        	if(!tempFlag){
            	for(Iterator<clientConnection> it=mainServer.getInstance().readyQ.iterator(); it.hasNext(); ){
    				clientConnection tmp = it.next();
    				if(tmp.getClientId().equals(tempId)){
    					it.remove();
    					tempFlag = true;
    					break;
    				}
    			}
        	}
        	this.join();
		} 
        catch (InterruptedException e) {
			e.printStackTrace();
		}
    }

    public void resetPingCnt(){
    	this.pingCnt = 3;
    }
    
}
